// pages/drug-list/drug-list.js
const { post, get } = require("../../utils/request");
const ApiConfig = require("../../config/api-config");

Page({
  data: {
    drugList: [],
    pageNum: 1,
    pageSize: 10,
    searchKeyword: '',
    loadingMore: false,
    allLoaded: false,
    scrollViewHeight: 0,
    showDeleteModal: false,
    currentDeleteId: null
  },

  onSearchInput(e) {
    this.setData({ searchKeyword: e.detail.value });
  },

  onSearchConfirm(e) {
    const keyword = (e.detail.value || '').trim();
    this.setData({ searchKeyword: keyword });
    this.loadDrugList(1, keyword); // 重新搜索
  },

  onLoad(options) {
    // 初始化：加载第一页，无搜索词
    this.loadDrugList(1, '');

    // 设置 scroll-view 高度
    const systemInfo = wx.getSystemInfoSync();
    // 减去搜索框高度（假设 100rpx ≈ 50px）和可能的状态栏/导航栏
    const searchBarHeight = 50; // px，可根据实际调整
    this.setData({
      scrollViewHeight: systemInfo.windowHeight - searchBarHeight
    });
  },

  // 统一的数据加载方法
  async loadDrugList(pageNum, keyword = '') {
    if (this.data.loadingMore) return;

    const isReset = pageNum === 1;
    this.setData({
      loadingMore: true,
      allLoaded: false,
      ...(isReset ? { drugList: [], pageNum: 1 } : {})
    });

    try {
      const newData = await this.fetchData(pageNum, keyword);
      if (isReset) {
        this.setData({
          drugList: newData,
          pageNum: newData.length < this.data.pageSize ? 1 : 2,
          loadingMore: false,
          allLoaded: newData.length === 0
        });
      } else {
        if (newData.length === 0) {
          this.setData({ allLoaded: true, loadingMore: false });
        } else {
          this.setData({
            drugList: [...this.data.drugList, ...newData],
            pageNum: this.data.pageNum + 1,
            loadingMore: false
          });
        }
      }
    } catch (error) {
      console.error('加载失败:', error);
      wx.showToast({ title: '加载失败', icon: 'none' });
      this.setData({ loadingMore: false });
    }
  },

  // 加载更多（滚动到底部）
  loadMoreData() {
    if (!this.data.allLoaded && !this.data.loadingMore) {
      this.loadDrugList(this.data.pageNum, this.data.searchKeyword);
    }
  },

  // 请求接口
  async fetchData(pageNum, keyword = '') {
    const url = ApiConfig.server.baseUrl + ApiConfig.endpoints.getDrugPageList;
    const queryParam = {
      pageNum: pageNum,
      pageSize: this.data.pageSize,
      name: keyword // 👈 确保传给后端
    };

    const res = await post(url, queryParam);
    // 假设成功结构为 { code: 200, data: { list: [...] } }
    if (res && res.code === 200 && Array.isArray(res.data?.list)) {
      return res.data.list;
    } else {
      console.warn('接口返回异常:', res);
      return [];
    }
  },

  // 长按删除相关逻辑（略，保持不变）
  onDrugLongPress(e) {
    const id = e.currentTarget.dataset.id;
    this.setData({ showDeleteModal: true, currentDeleteId: id });
  },

  hideDeleteModal() {
    this.setData({ showDeleteModal: false, currentDeleteId: null });
  },

  async confirmDelete() {
    const id = this.data.currentDeleteId;
    if (!id) return;

    const url = ApiConfig.server.baseUrl + ApiConfig.endpoints.deleteDrugById;
    // ⚠️ 强烈建议改为 POST 或 DELETE，不要用 GET 传参删数据
    const res = await post(url, { id }); // 改为 post

    if (res && res.code === 200) {
      wx.showToast({ title: '已删除', icon: 'success' });
      this.hideDeleteModal();
      // 刷新当前搜索结果
      this.loadDrugList(1, this.data.searchKeyword);
    } else {
      wx.showToast({ title: '删除失败', icon: 'none' });
    }
  }
});